package mines.eerock.sphero.bowling.audiobutton;

import android.R;
import android.app.Activity;
import android.media.MediaPlayer;

public class AudioJackButton {
	
    // AOSP audio tools
    private MediaPlayer mPlayer;
    private AudioReader mRecorder;
    // array to store the audio info
    short[] mMicBuffer = new short[SPECTRUM_SIZE];
    // Buffer read size (sections of spectrum)
    private final static int SPECTRUM_SIZE = 256;
    // Microphone Encoding
    private final static int MIC_SAMPLE_RATE = 8000;
    private final static int BUTTON_PRESS_THRESHOLD = 100;
    // Max double and position of Frequency
    protected double mAvgEnergy = 0;
    
    protected boolean mIsButtonPressed = false;
    protected boolean mJustClicked = false;
	
    /**
     * Set up Microphone to record input data
     * @param act
     */
    public AudioJackButton() {}
    
    public double getAvgEnergy() {
    	return mAvgEnergy;
    }

	/**
	 * Compute waveform energy of amplitudes
	 */
	private void receiveAudio(short[] buffer) {
		// compute average energy of the sound input
		double totEnergy = 0;
		synchronized(mMicBuffer) {
			for(int i = 0; i < buffer.length; i++) {
				totEnergy += (((double)buffer[i]*.001*(double)buffer[i]*.001));
			}
		}
		mAvgEnergy = totEnergy/SPECTRUM_SIZE;
		
		// if the average energy is greater than threshold, then we have a signal and the button has been pressed
		if(mAvgEnergy > BUTTON_PRESS_THRESHOLD) {
			if( !mJustClicked ) {
				mIsButtonPressed = true;
				mJustClicked = true;
				//mRecorder.stopReader();
				mPlayer.stop();
			}
		}
		else {
			mJustClicked = false;
		}
	}	

	/**
	 * Start Listening for Button presses again
	 */
	public void startButtonListener(Activity act) {
		mIsButtonPressed = false;
		// Setup Audio Tone for Button Press
        // Construct AudioRecord to record audio from microphone with sample rate of 8000Hz
        mPlayer = MediaPlayer.create(act.getApplicationContext(), mines.eerock.sphero.bowling.R.raw.tone);
        mPlayer.setLooping(true);  
       // mPlayer.setVolume(0.0f, 1.0f);      
		// Start playing tone
        mPlayer.start(); 
        //setupButton(act);
	}

	/*
	 * Start checking for audio input from the output wave
	 */ 
	public void setupButton(Activity act) { 
    	mRecorder = new AudioReader(act);	
        mRecorder.startReader(MIC_SAMPLE_RATE, SPECTRUM_SIZE, new AudioReader.Listener() {
            @Override
            public final void onReadComplete(short[] buffer) {
            	if( !mIsButtonPressed ) {            		
                	receiveAudio(buffer);
            	}
            }
            @Override
            public void onReadError(int error) {
                handleError(error);
            }
        });
	} 
	
	/**
	 * Handle Microphone error
	 * @param error
	 */
	private void handleError(int error) {
		if( error == 1 ) {
			int i = 0;
			i++;
		}
	}
	
	/**
	 * Called to check whether the button has been pressed in this iteration
	 * It will always be false unless you call startButtonListener()
	 * @return
	 */
	public boolean isButtonPressed() {
		return mIsButtonPressed;
	}

    /**
     * cleanUp()
     * 
     * Called on App termination or stall, releases audio resources
     */
    public void cleanUp()
    {
      if (mPlayer != null)
      {
    	mPlayer.stop();
        mPlayer.release();
        mPlayer = null;
      }
      
      if (mRecorder != null)
      {
    	mRecorder.stopReader();
    	mRecorder = null;
      }
    }
}